package com.itheima.itheima_health.controller.admin.WorkloadstatController;

import com.itheima.itheima_health.constant.MessageConstant;
import com.itheima.itheima_health.entity.Result;
import com.itheima.itheima_health.service.WorkloadstatService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工作统计相关接口
 */
@RestController
@RequestMapping("/report")
@Slf4j
@Api(tags = "工作统计相关接口")
public class WorkloadstatController {
    @Autowired
    private WorkloadstatService workloadstatService;

    /**
     * 获取会员统计数据
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result GetWorkloadstat(){
        log.info("获得当前日期之前12个月的日期   当前日期:{}", LocalDateTime.now());
        Map<String,Object> map = new HashMap<>();
        //获取最近一年的格式化月份
        List<String> months = workloadstatService.GetRecentrYear(LocalDate.now());
        map.put("months",months);

        //根据月份数组查询最近一年的会员数
        List<Integer> memberCount = (workloadstatService.GetNowMonthsUserNum());

        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }
    /**
     * 套餐占比统计
     * @return
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        List<Map<String, Object>> list = workloadstatService.findSetmealCount();

        Map<String,Object> map = new HashMap<>();
        map.put("setmealCount",list);

        List<String> setmealNames = new ArrayList<>();
        for(Map<String,Object> m : list){
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames",setmealNames);

        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    /**
     * 获取运营统计数据
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        Map<String, Object> result = workloadstatService.getBusinessReport();
        log.info("获取运营统计数据");
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,result);
    }
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try{
            //调用报表服务获取报表数据
            Map<String, Object> result = workloadstatService.getBusinessReport();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            LocalDate reportDate = (LocalDate) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //获得Excel模板文件绝对路径
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/report_template.xlsx");

            XSSFWorkbook excel = new XSSFWorkbook(in);
            //读取模板文件创建Excel表格对象
            //填充数据
            XSSFSheet sheet = excel.getSheetAt(0);

            //获取第三行
            XSSFRow row3 = sheet.getRow(2);
            //获取第五行
            XSSFRow row5 = sheet.getRow(4);
            //获取第六行
            XSSFRow row6 = sheet.getRow(5);
            //获取第八行
            XSSFRow row8 = sheet.getRow(7);
            //获取第九行
            XSSFRow row9 = sheet.getRow(8);
            //获取第十行
            XSSFRow row10 = sheet.getRow(9);

            //日期
            row3.getCell(5).setCellValue(String.valueOf(reportDate));
            //新增会员数（本日）
            row5.getCell(5).setCellValue(todayNewMember);
            //总会员数
            row5.getCell(7).setCellValue(totalMember);
            //本周新增会员数
            row6.getCell(5).setCellValue(thisWeekNewMember);
            //本月新增会员数
            row6.getCell(7).setCellValue(thisMonthNewMember);
            //今日预约数
            row8.getCell(5).setCellValue(todayOrderNumber);
            //今日到诊数
            row8.getCell(7).setCellValue(todayVisitsNumber);
            //本周预约数
            row9.getCell(5).setCellValue(thisWeekOrderNumber);
            //本周到诊数
            row9.getCell(7).setCellValue(thisWeekVisitsNumber);
            //本月预约数
            row10.getCell(5).setCellValue(thisMonthOrderNumber);
            //本月到诊数
            row10.getCell(7).setCellValue(thisMonthVisitsNumber);

            XSSFRow rowrowNum = sheet.getRow(0);
            int rowNum = 12;
            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                rowrowNum = sheet.getRow(rowNum ++);
                rowrowNum.getCell(4).setCellValue(name);//套餐名称
                rowrowNum.getCell(5).setCellValue(setmeal_count);//预约数量
                rowrowNum.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //通过输出流进行文件下载
            //3.通过输出流将Rxcel文件下载到客服端浏览器
            /*ServletOutputStream out = response.getOutputStream();
            excel.write(out);
*/
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            excel.write(out);

            out.flush();
            out.close();
            excel.close();

            return null;
        }catch (Exception e){
            log.info("Dbug:{}",e.getMessage());
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL,null);
        }
    }

    /**
     * 导出运营数据到pdf并提供客户端下载
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 调用报表服务获取报表数据
            Map<String, Object> result = workloadstatService.getBusinessReport();
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            // 使用 ClassLoader 获取模板文件的输入流
            InputStream jrxmlInputStream = this.getClass().getClassLoader().getResourceAsStream("template/health_business3.jrxml");
            if (jrxmlInputStream == null) {
                throw new FileNotFoundException("为找到文件: template/health_business3.jrxml");
            }

            // 编译模板
            JasperReport jasperReport = JasperCompileManager.compileReport(jrxmlInputStream);

            // 填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, result, new JRBeanCollectionDataSource(hotSetmeal));

            // 设置响应头
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=report.pdf");

            // 输出文件
            try (ServletOutputStream out = response.getOutputStream()) {
                JasperExportManager.exportReportToPdfStream(jasperPrint, out);
            }

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }
    }
}
